package com.zide.platform.controller;

import com.zide.auth.domain.entity.platform.PlatformRole;
import com.zide.auth.domain.entity.platform.PlatformUser;
import com.zide.auth.domain.entity.platform.dept.PlatformDept;
import com.zide.auth.service.PlatformUserService;
import com.zide.auth.utils.ZiDeContext;
import com.zide.auth.vo.result.PlatformUserResultVO;
import com.zide.auth.vo.search.PlatformUserSearchVO;
import com.zide.common.core.domain.CommonResult;
import com.zide.common.core.domain.PageResult;
import com.zide.common.enums.BusinessType;
import com.zide.common.utils.StringUtils;
import com.zide.file.utils.poi.ExcelUtil;
import com.zide.platform.service.PlatformDeptService;
import com.zide.platform.service.PlatformPostService;
import com.zide.platform.service.PlatformRoleService;
import com.zide.platform.vo.result.role.PlatformRoleResultVO;
import com.zide.platform.vo.search.dept.PlatformDeptSearchVO;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.ArrayUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import java.util.List;
import java.util.stream.Collectors;

import static com.zide.common.core.domain.CommonResult.getResult;

/**
 * 用户信息
 *
 * @author xguo
 */
@Tag(name = "后台管理 - 用户信息管理")
@RestController
@RequestMapping("/platform/user")
@RequiredArgsConstructor
public class PlatformUserController {
    private final PlatformUserService userService;
    private final PlatformRoleService roleService;
    private final PlatformDeptService deptService;
    private final PlatformPostService postService;
 
    /**
     * 获取用户列表
     */
    @GetMapping("/page")
    public CommonResult list(PlatformUserSearchVO searchVO) {
        PageResult<PlatformUserResultVO> result = userService.selectPage(searchVO);
        return CommonResult.success().put("data",result);
    }
    
    @PostMapping("/export")
    public void export(HttpServletResponse response, PlatformUser user) {
        List<PlatformUserResultVO> list = userService.selectUserList(user);
        ExcelUtil<PlatformUserResultVO> util = new ExcelUtil<>(PlatformUserResultVO.class);
        util.exportExcel(response, list, "用户数据");
    }

    @PostMapping("/importData")
    public CommonResult importData(MultipartFile file, boolean updateSupport) throws Exception {
        ExcelUtil<PlatformUser> util = new ExcelUtil<PlatformUser>(PlatformUser.class);
        List<PlatformUser> userList = util.importExcel(file.getInputStream());
        Long userId = ZiDeContext.getPlatformUserId();
        String message = userService.importUser(userList, updateSupport, userId);
        return CommonResult.success(message);
    }

    @PostMapping("/importTemplate")
    public void importTemplate(HttpServletResponse response) {
        ExcelUtil<PlatformUser> util = new ExcelUtil<PlatformUser>(PlatformUser.class);
        util.importTemplateExcel(response, "用户数据");
    }

    /**
     * 根据用户编号获取详细信息
     */
    @GetMapping(value = {"/","/{userId}"})
    public CommonResult getInfo(@PathVariable(value = "userId", required = false) Long userId) {
        CommonResult ajax = CommonResult.success();
        List<PlatformRole> roles = roleService.selectRoleAll();
        ajax.put("roles", PlatformUser.isAdmin(userId) ? roles : roles.stream().filter(r -> !r.isAdmin()).collect(Collectors.toList()));
        ajax.put("posts", postService.selectPostAll());
        if (StringUtils.isNotNull(userId)) {
            PlatformUser sysUser = userService.selectUserById(userId);
            ajax.put(CommonResult.DATA_TAG, sysUser);
            ajax.put("postIds", postService.selectPostListByUserId(userId));
            ajax.put("roleIds", sysUser.getRoles().stream().map(PlatformRole::getId).collect(Collectors.toList()));
        }
        return ajax;
    }

    /**
     * 新增用户
     */
    @PostMapping
    public CommonResult add(@Validated @RequestBody PlatformUser user) {
        return getResult(userService.insertUser(user));
    }

    /**
     * 修改用户
     */
    @PutMapping
    public CommonResult edit(@Validated @RequestBody PlatformUser user) {
        return getResult(userService.updateUser(user));
    }

    /**
     * 删除用户
     */
    @DeleteMapping("/{userIds}")
    public CommonResult remove(@PathVariable Long[] userIds) {
        if (ArrayUtils.contains(userIds, ZiDeContext.getPlatformUserId())) {
            return CommonResult.error("当前用户不能删除");
        }
        return CommonResult.success(userService.deleteUserByIds(userIds));
    }

    /**
     * 重置密码
     */
    @PutMapping("/resetPwd")
    public CommonResult resetPwd(@RequestBody PlatformUser user) {
        return CommonResult.getResult(userService.resetPwd(user));
    }

    /**
     * 状态修改
     */
    @PutMapping("/changeStatus")
    public CommonResult changeStatus(@RequestBody PlatformUser user) {
        return CommonResult.getResult(userService.updateUserStatus(user));
    }

    /**
     * 根据用户编号获取授权角色
     */
    @GetMapping("/authRole/{userId}")
    public CommonResult authRole(@PathVariable("userId") Long userId) {
        CommonResult ajax = CommonResult.success();
        PlatformUser user = userService.selectUserById(userId);
        List<PlatformRoleResultVO> roles = roleService.selectRolesByUserId(userId);
        ajax.put("user", user);
        ajax.put("roles", PlatformUser.isAdmin(userId) ? roles : roles.stream().filter(r -> !r.isAdmin()).collect(Collectors.toList()));
        return ajax;
    }

    /**
     * 用户授权角色
     */
    @PutMapping("/authRole")
    public CommonResult insertAuthRole(Long userId, Long[] roleIds) {
        userService.insertUserAuth(userId, roleIds);
        return CommonResult.success();
    }

    /**
     * 获取部门树列表
     */
    @GetMapping("/deptTree")
    public CommonResult deptTree(PlatformDeptSearchVO dept) {
        return CommonResult.success(deptService.selectDeptTreeList(dept));
    }
}
